jQuery(document).ready(function($) {
    // Populate sortable list based on form input
    $('#post-type, #category-slug, #slugs').on('change', function() {
        var postType = $('#post-type').val();
        var categorySlug = $('#category-slug').val();
        var slugs = $('#slugs').val().split(',').filter(Boolean);

        $.ajax({
            url: nxCustomSort.ajax_url,
            method: 'POST',
            data: {
                action: 'nx_custom_sort_get_items',
                post_type: postType,
                category_slug: categorySlug,
                slugs: slugs,
                nonce: nxCustomSort.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#sortable-list').html('');
                    response.data.forEach(function(item) {
                        $('#sortable-list').append(
                            '<li class="sortable-item" data-id="' + item.id + '">' + item.title + '</li>'
                        );
                    });
                    new Sortable(document.getElementById('sortable-list'), {
                        animation: 150
                    });
                }
            }
        });
    });

    // Save sorting rule
    $('#nx-custom-sort-form').on('submit', function(e) {
        e.preventDefault();
        var sortOrder = [];
        $('#sortable-list .sortable-item').each(function() {
            sortOrder.push($(this).data('id'));
        });

        $.ajax({
            url: nxCustomSort.ajax_url,
            method: 'POST',
            data: {
                action: 'nx_custom_sort_save_rule',
                rule_name: $('#rule-name').val(),
                post_type: $('#post-type').val(),
                category_slug: $('#category-slug').val(),
                slugs: $('#slugs').val(),
                sort_order: sortOrder,
                nonce: nxCustomSort.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('Rule saved successfully!');
                } else {
                    alert('Error: ' + response.data);
                }
            }
        });
    });

    // Create page
    $('#create-page-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: nxCustomSort.ajax_url,
            method: 'POST',
            data: {
                action: 'nx_custom_sort_create_page',
                rule_id: $('#rule-id').val(),
                nonce: nxCustomSort.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('Page created with ID: ' + response.data.page_id);
                } else {
                    alert('Error: ' + response.data);
                }
            }
        });
    });
});
